﻿using System;
using System.Threading.Tasks;
using System.Windows;
using Castle.Windsor;
using Mammoth.Factories;
using Mammoth.Installers;
using Mammoth.Repositories;
using Mammoth.Services;
using MySql.Data.MySqlClient;

namespace Mammoth
{
    /// <summary>
    /// Interaction logic for SplashScreen.xaml
    /// </summary>
    public partial class SplashScreen : Window
    {
        ITypeFactory factory;

        public SplashScreen()
        {
            InitializeComponent();
        }

        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);
            InitializeAsync();
        }

        void InitializeAsync()
        {
            Task.Factory.StartNew(Initialize);
        }

        private void Initialize()
        {
            var inf = new InstallerFactory();
            var c = new WindsorContainer();
            c.Install(inf.GetInstaller());
            factory = c.Resolve<ITypeFactory>();

            try
            {
                var init = factory.Create<IAppInitializer>();
                init.Initialize();
                ThreadSafeShowMainWindow();
            }
            catch (MySqlException)
            {
                MessageBox.Show("Gagal melakukan konesi ke MySQL. Server MySQL offline atau informasi database di file konfigurasi salah", "Galat");
                ThreadSafeClose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                ThreadSafeClose();
            }
        }

        void ThreadSafeShowMainWindow()
        {
            Dispatcher.Invoke(ShowMainWindow);
        }

        void ShowMainWindow()
        {
            var w = factory.Create<MainWindow>();
            w.Show();
            Close();
        }

        void ThreadSafeClose()
        {
            Dispatcher.Invoke(Close);
        }
    }
}
